//
//  ComposePicView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/26.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposePicView: UICollectionView {
    
    //定义闭包
    var composeImgClosure:(() -> ())?
    
    //创建空的存储图片的数组
    var images: [UIImage] = []
    
    let ComposePicViewID = "ComposePicViewCell"
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        //注册cell
        self.registerClass(ComposePicViewCell.self, forCellWithReuseIdentifier: ComposePicViewID)
        
        self.dataSource = self
        self.delegate = self
        
        let flowlayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置layout属性
        let margin: CGFloat = 10
        let itemW: CGFloat = (SCREENW - 2 * margin) / 3
        let itemH: CGFloat = itemW
        flowlayout.itemSize = CGSize(width: itemW, height: itemH)
        
        flowlayout.minimumInteritemSpacing = 0
        flowlayout.minimumLineSpacing = 0
    }
    
    // MARK: - 提供给外界添加图片方法
    func addImage(img: UIImage){
        
        //判断图片的数量,最多显示9张
        if images.count < 9{
            
            //            print("append前\(images.count)")
            images.append(img)
            //            print("append后\(images.count)")
            reloadData()
            
        }else{
            SVProgressHUD.showErrorWithStatus("图片选择已达上限")
        }
    }
}

extension ComposePicView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //判断如果count为0 或者 9,则保留,else count + 1
        self.hidden = images.count == 0 ? true : false
        return (images.count == 0 || images.count == 9) ? images.count :images.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ComposePicViewID, forIndexPath: indexPath) as! ComposePicViewCell
        
        //        cell.backgroundColor = RandomColor
        
        //看到闭包 -> ***** 马上想到是否循环引用
        //VC -> cell -> 闭包 -> VC (循环引用)
        cell.deleteButtonClosure = { [weak self] in
            
            //设置要执行的闭包
            self?.images.removeAtIndex(indexPath.item)
            //刷新
            self?.reloadData()
        }
        
        //判断,把图片数组里最后一张设置成加号按钮
        if indexPath.item == images.count{
            
            //代表是加号按钮
            cell.img = nil
            
        }else{
            
            cell.img = images[indexPath.item]
        }
        return cell
    }
    
    //点击cell ,回调选择图片的方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count{
            
            //执行闭包
            composeImgClosure?()
        }
    }
}

class ComposePicViewCell: UICollectionViewCell{
    
    var deleteButtonClosure:(() -> ())?
    
    var img: UIImage?{
        
        didSet{
            
            if img == nil{
                
                //代表是加号按钮
                imgView.image = UIImage(named: "compose_pic_add")
                //隐藏x号
                deleteButton.hidden = true
            }else{
                
                imgView.image = img
                deleteButton.hidden = false
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //添加控件
        contentView.addSubview(imgView)
        contentView.addSubview(deleteButton)
        
        //添加约束
        imgView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
    }
    
    @objc private func didClickDeleteButton(){
        
        print("didClickDeleteButton")
        //执行删除图片的闭包
        deleteButtonClosure?()
    }
    
    //懒加载
    private lazy var imgView: UIImageView = UIImageView()
    private lazy var deleteButton: UIButton = {
        
        let deleteBtn = UIButton()
        
        //点击事件
        deleteBtn.addTarget(self, action: "didClickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        deleteBtn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return deleteBtn
    }()
}



